#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time   : 2022-06-06 17:51:04
# @Author : 搬砖客

import json
import traceback
from typing import Text, Dict, Union, List
import yaml
import jsonpath
import csv
from utils.logging_utils.log_util import write_log, write_error_log, write_warning_log
from common.path_setting import ensure_path_sep


# 读取csv文件
def read_csv_file(csv_path: Text) -> List:
    """

    :param csv_path: csv路径
    :return:
    """
    csv_data_list = []
    with open(ensure_path_sep("\\data" + csv_path), mode="r", encoding="utf-8") as file:
        csv_data = csv.reader(file)
        for row in csv_data:
            csv_data_list.append(row)
        return csv_data_list


# 读取测试用例使用该方法，以前的读取方法在这个方法中调用和解析
def read_testcase_yaml(yaml_path: Text) -> Union[Dict, List]:
    """

    :param yaml_path: 测试用例文件
    :return:
    """
    try:
        # with open(config_util.DATA_PATH + yaml_path, mode="r", encoding="utf-8") as file:
        with open(ensure_path_sep("\\data" + yaml_path), mode="r", encoding="utf-8") as file:
            args = yaml.load(file, Loader=yaml.FullLoader)
            # 当yaml文件大于等于两个字典的时候，不进行csv数据驱动
            if len(args) >= 2:
                return args
            else:
                # 判断用例中是否有csv关键字"parameters"
                if jsonpath.jsonpath(*args, '$.parameters'):
                    new_args = analysis_parameters(*args)
                    return new_args
                else:
                    return args
    except Exception as e:
        write_log("错误用例名称为：{}".format(args['name']))
        write_error_log("读取用例文件异常，异常信息为：%s" % str(traceback.format_exc()))


# 分析参数化
def analysis_parameters(args: Union[List, Dict]) -> Union[List, Dict]:
    try:
        args_keys = dict(args).keys()
        if "parameters" in args_keys:
            args_str = str(eval(json.dumps(args).replace('null', '" "')))
            for key, value in dict(args['parameters']).items():
                key_list = str(key).split("-")
                # 规范csv的数据的写法
                length_flag = True
                csv_data_list = read_csv_file(value)
                one_row_csv_data = csv_data_list[0]
                for csv_data in csv_data_list:
                    if len(csv_data) != len(one_row_csv_data):
                        length_flag = False
                        write_warning_log("文件：‘{}’中存在错误格式，错误内容为：‘{}’".format(value, csv_data))
                        break
                # 解析
                new_args = []
                if length_flag is True:
                    # row代表行,column代表列
                    for row in range(1, len(csv_data_list)):
                        temp_args = args_str  # 保持args_str数据不变
                        for column in range(0, len(csv_data_list[row])):
                            if csv_data_list[0][column] in key_list:
                                temp_args = temp_args.replace("$csv{" + csv_data_list[0][column] + "}",
                                                              csv_data_list[row][column])
                        new_args.append(eval(temp_args))  # 使用eval将temp_args字符串转换回字典格式
                return new_args
        else:
            return args
    except Exception as e:
        write_log("错误用例名称为：{}".format(args['name']))
        write_error_log("分析parameters参数化异常，异常信息为：%s" % str(traceback.format_exc()))
